package com.xbzl.cly_demo.utils;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xbzl.cly_demo.entity.Vehicle;
import com.xbzl.cly_demo.entity.VehicleAbnormalRecords;
import com.xbzl.cly_demo.entity.VehicleStatus;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class MessageConverter {
    //mqtt消息转换为车辆状态
    public static VehicleStatus convertMessageToVehicleStatus(String message) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(message);
        JsonNode bodyNode = rootNode.path("body");

        return VehicleStatus.builder()
                .vehicleVin(bodyNode.path("vehicleId").asText())
                .timestampGnss(bodyNode.path("timestampGNSS").asLong())
                .velocityGnss(bodyNode.path("velocityGNSS").asDouble())
                .longitude(new BigDecimal(bodyNode.path("position").path("longitude").asText("0")))
                .latitude(new BigDecimal(bodyNode.path("position").path("latitude").asText("0")))
                .heading(bodyNode.path("heading").asDouble())
                .accelerationLon(bodyNode.path("accelerationLon").asDouble())
                .accelerationLat(bodyNode.path("accelerationLat").asDouble())
                .yawRate(bodyNode.path("yawRate").asInt())
                .accelPos(bodyNode.path("accelPos").asInt())
                .engineSpeed(bodyNode.path("engineSpeed").asInt())
                .engineTorque(bodyNode.path("engineTorque").asInt())
                .brakeFlag(bodyNode.path("brakeFlag").asInt())
                .brakePos(bodyNode.path("brakePos").asInt())
                .brakePressure(bodyNode.path("brakePressure").asInt())
                .fuelConsumption(bodyNode.path("fuelConsumption").asInt())
                .createdAt(LocalDateTime.now())
                .build();
    }

    //mqtt消息转换为车辆基本信息
    public static Vehicle convertMessageToVehicle(String message) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(message);
        JsonNode bodyNode = rootNode.path("body");
        JsonNode extNode = bodyNode.path("ext");

        return Vehicle.builder()
                .vin(bodyNode.path("vehicleId").asText())
                .plateNo(extNode.path("plateNo").asText())
                .deviceName(extNode.path("deviceName").asText())
                .build();
    }
}

//package com.xbzl.cly_demo.utils;
//
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.xbzl.cly_demo.entity.VehicleLocation;
//import com.xbzl.cly_demo.entity.VehicleAbnormalRecords;
//import com.xbzl.cly_demo.entity.Vehicles;
//
//import java.math.BigDecimal;
//import java.time.Instant;
//import java.time.LocalDateTime;
//import java.time.ZoneId;
//
//public class MessageConverter {
//
//    /**
//     * 将 MQTT 消息 JSON 字符串转换为 VehicleLocation 实体
//     *
//     * @param message 接收到的消息字符串
//     * @return 转换后的 VehicleLocation 对象
//     * @throws Exception 转换过程可能抛出异常
//     */
//    public static VehicleLocation convertMessageToVehicleLocation(String message) throws Exception {
//        ObjectMapper mapper = new ObjectMapper();
//        JsonNode root = mapper.readTree(message);
//
//        // 获取 header 与 body 部分
//        JsonNode headerNode = root.get("header");
//        JsonNode bodyNode = root.get("body");
//
//        // 从 header 中获取时间戳并转换为 LocalDateTime
//        long timestamp = headerNode.get("timestamp").asLong();
//        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
//
//        // 从 body 中获取位置信息
//        JsonNode positionNode = bodyNode.get("position");
//        BigDecimal longitude = new BigDecimal(positionNode.get("longitude").asText());
//        BigDecimal latitude = new BigDecimal(positionNode.get("latitude").asText());
//
//        // 获取 vehicleId 字段，此处需做字符串到 Long 的映射
//        String vehicleIdStr = bodyNode.get("vehicleId").asText();
//        // 示例：如果 vehicleId 为 "self_vehicle"，则映射为 1L；实际情况请根据业务逻辑处理
//        Long vehicleId = "self_vehicle".equals(vehicleIdStr) ? 1L : Long.parseLong(vehicleIdStr);
//
//        // 构造 VehicleLocation 实体
//        VehicleLocation vehicleLocation = new VehicleLocation();
//        vehicleLocation.setVehicleid(vehicleId);
//        vehicleLocation.setLongitude(longitude);
//        vehicleLocation.setLatitude(latitude);
//        vehicleLocation.setTimestamp(dateTime);
//
//        return vehicleLocation;
//    }
//
//    /**
//     * 将 MQTT 消息 JSON 字符串转换为 Vehicles 实体
//     *
//     * @param message 接收到的消息字符串
//     * @return 转换后的 Vehicles 对象
//     * @throws Exception 转换过程可能抛出异常
//     */
//    public static Vehicles convertMessageToVehicles(String message) throws Exception {
//        ObjectMapper mapper = new ObjectMapper();
//        JsonNode root = mapper.readTree(message);
//        JsonNode bodyNode = root.get("body");
//
//        // 获取 vehicleId 并转换映射，同 VehicleLocation 的处理
//        String vehicleIdStr = bodyNode.get("vehicleId").asText();
//        Long vehicleId = "self_vehicle".equals(vehicleIdStr) ? 1L : Long.parseLong(vehicleIdStr);
//
//        // 从 ext 节点中获取 plateNo 和 engineType，其他字段可根据业务自行设置默认值
//        JsonNode extNode = bodyNode.get("ext");
//        String plateNum = extNode.get("plateNo").asText();
//        // 此处以 engineType 作为车辆类型（vehicletype），可根据实际情况调整
//        String vehicleType = extNode.get("engineType").asText();
//
//        // driveMode 可作为状态字段
//        String status = bodyNode.get("driveMode").asText();
//
//        // 示例：总里程、总时长、平均速度等字段未在消息中体现，设置默认值为 0
//        BigDecimal totalDistance = BigDecimal.ZERO;
//        BigDecimal totalDuration = BigDecimal.ZERO;
//        BigDecimal averageSpeed = BigDecimal.ZERO;
//
//        Vehicles vehicles = new Vehicles();
//        vehicles.setVehicleid(vehicleId);
//        vehicles.setVehicletype(vehicleType);
//        // 示例中 owner 字段设置为 vehicleId，可按实际业务逻辑映射
//        vehicles.setOwner(vehicleId);
//        vehicles.setStatus(status);
//        vehicles.setTotaldistance(totalDistance);
//        vehicles.setTotalduration(totalDuration);
//        vehicles.setAveragespeed(averageSpeed);
//        vehicles.setPlatenum(plateNum);
//
//        return vehicles;
//    }
//
//    /**
//     * 将 MQTT 消息 JSON 字符串转换为 VehicleAbnormalRecords 实体
//     *
//     * @param message 接收到的消息字符串
//     * @return 转换后的 VehicleAbnormalRecords 对象，如果消息中无异常则返回 null
//     * @throws Exception 转换过程可能抛出异常
//     */
//    public static VehicleAbnormalRecords convertMessageToVehicleAbnormalRecords(String message) throws Exception {
//        ObjectMapper mapper = new ObjectMapper();
//        JsonNode root = mapper.readTree(message);
//        JsonNode headerNode = root.get("header");
//        JsonNode bodyNode = root.get("body");
//
//        // 获取 header 中的时间戳并转换为 LocalDateTime
//        long timestamp = headerNode.get("timestamp").asLong();
//        LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
//
//        // 获取 vehicleId 字段的映射，同上处理
//        String vehicleIdStr = bodyNode.get("vehicleId").asText();
//        Long vehicleId = "self_vehicle".equals(vehicleIdStr) ? 1L : Long.parseLong(vehicleIdStr);
//
//        // 根据加速度信息判断是否存在异常
//        double accelerationLon = bodyNode.get("accelerationLon").asDouble();
//        double accelerationLat = bodyNode.get("accelerationLat").asDouble();
//        String type = null;
//        if (accelerationLon < -5.0) {
//            type = "急刹车";
//        } else if (accelerationLon > 5.0) {
//            type = "急加速";
//        } else if (accelerationLat > 100.0) {
//            type = "侧向异常加速度";
//        }
//
//        // 如果没有异常，返回 null
//        if (type == null) {
//            return null;
//        }
//
//        VehicleAbnormalRecords record = new VehicleAbnormalRecords();
//        record.setVehicleid(vehicleId);
//        record.setTime(time);
//        record.setType(type);
//
//        return record;
//    }
//}
